package com.example.umbrella;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.umbrella.adapter.CharacteristicAdapter;
import com.example.umbrella.util.DataConverter;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.snackbar.Snackbar;

import java.util.List;

public class DeviceDetailActivity extends AppCompatActivity {
    private BluetoothGatt bluetoothGatt;
    private View loadingView;
    private TextView loadingText;
    private RecyclerView characteristicsList;
    private CharacteristicAdapter characteristicAdapter;
    private String targetServiceUuid;
    // 添加定时器相关变量
    private Handler handler = new Handler();
    private static final int READ_INTERVAL = 500; // 1秒刷新一次，可以根据需要调整
    private View circle;

    private TextView light;
    private Button shot;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_detail);

        initViews();
        initToolbar();

        String deviceAddress = getIntent().getStringExtra("deviceAddress");
        targetServiceUuid = getIntent().getStringExtra("serviceUuid");

        if (deviceAddress != null) {
            showLoading("正在连接设备...");
            connectToDevice(deviceAddress);
        }
    }

    private void initToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
    }

    private void initViews() {
        loadingView = findViewById(R.id.loading_view);
        loadingText = loadingView.findViewById(R.id.loading_text);
        characteristicsList = findViewById(R.id.characteristics_list);
        characteristicsList.setLayoutManager(new LinearLayoutManager(this));
        characteristicAdapter = new CharacteristicAdapter();
        characteristicsList.setAdapter(characteristicAdapter);

        light = findViewById(R.id.light);
        shot = findViewById(R.id.shot_button);
        circle = findViewById(R.id.circle_indicator);


        // 设置 shot 按钮点击事件
        shot.setOnClickListener(v -> {
            try {
                writeCharacteristic("1");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

    }
    // 添加定时任务
    private final Runnable readRunnable = new Runnable() {
        @Override
        public void run() {
            readCharacteristics(bluetoothGatt);
            handler.postDelayed(this, READ_INTERVAL);
        }
    };


    private void writeCharacteristic(String number) throws InterruptedException {
        if (bluetoothGatt != null) {
            // 遍历服务找到可写特征值
            for (BluetoothGattService service : bluetoothGatt.getServices()) {
                if (service.getUuid().toString().equals(targetServiceUuid)) {
                    for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
                        // 检查是否为可写特征值
                        if ((characteristic.getProperties() &
                                (BluetoothGattCharacteristic.PROPERTY_WRITE |
                                        BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) != 0) {

                            // 设置要写入的值
                            characteristic.setValue(number.getBytes());
                            Thread.sleep(1000);
                            shot.setActivated(true);
                            characteristic.setValue("0".getBytes());
                            // 检查权限并写入
                            if (ActivityCompat.checkSelfPermission(this,
                                    Manifest.permission.BLUETOOTH_CONNECT) ==
                                    PackageManager.PERMISSION_GRANTED) {
                                bluetoothGatt.writeCharacteristic(characteristic);
                            }
                            break;
                        }
                    }
                    break;
                }
            }
        }
    }

    private void showLoading(String message) {
        if (loadingText != null) {
            loadingText.setText(message);
        }
        if (loadingView != null) {
            loadingView.setVisibility(View.VISIBLE);
        }
    }

    private void hideLoading() {
        if (loadingView != null) {
            loadingView.setVisibility(View.GONE);
        }
    }

    private void connectToDevice(String deviceAddress) {
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT)
            != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "缺少蓝牙连接权限", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
        bluetoothGatt = device.connectGatt(this, false, gattCallback);
    }

    private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                if (newState == BluetoothGatt.STATE_CONNECTED) {
                    runOnUiThread(() -> {
                        showLoading("正在获取设备信息...");
                    });
                    if (ActivityCompat.checkSelfPermission(DeviceDetailActivity.this,
                        Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                        gatt.discoverServices();
                    }
                } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                    runOnUiThread(() -> {
                        hideLoading();
                        showError("设备连接已断开");
                    });
                }
            } else {
                runOnUiThread(() -> {
                    hideLoading();
                    showError("连接失败，错误码: " + status);
                });
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.d("DeviceDetail", "开始检查服务: " + targetServiceUuid);

                BluetoothGattService targetService = null;
                for (BluetoothGattService service : gatt.getServices()) {
                    String serviceUuid = service.getUuid().toString();
                    Log.d("DeviceDetail", "发现服务: " + serviceUuid);
                    if (serviceUuid.equals(targetServiceUuid)) {
                        targetService = service;
                        break;
                    }
                }

                if (targetService == null) {
                    Log.e("DeviceDetail", "未找到目标服务");
                    runOnUiThread(() -> {
                        hideLoading();
                        showError("未找到目标服务");
                    });
                    return;
                }

                int tempReadableCount = 0;
                int tempWritableCount = 0;

                Log.d("DeviceDetail", "开始检查特征值:");
                for (BluetoothGattCharacteristic characteristic : targetService.getCharacteristics()) {
                    int properties = characteristic.getProperties();
                    Log.d("DeviceDetail", "特征值: " + characteristic.getUuid() +
                          ", 属性: " + properties);

                    if ((properties & BluetoothGattCharacteristic.PROPERTY_READ) != 0) {
                        tempReadableCount++;
                        Log.d("DeviceDetail", "可读特征值 +1，当前: " + tempReadableCount);
                    }
                    if ((properties & (BluetoothGattCharacteristic.PROPERTY_WRITE
                        | BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) != 0) {
                        tempWritableCount++;
                        Log.d("DeviceDetail", "可写特征值 +1，当前: " + tempWritableCount);
                    }
                }

                final int readableCount = tempReadableCount;
                final int writableCount = tempWritableCount;

                Log.d("DeviceDetail", String.format("特征值统计完成 - 可读: %d, 可写: %d",
                      readableCount, writableCount));

                if (readableCount != 1 || writableCount != 1) {
                    Log.d("DeviceDetail", "特征值数量不符合要求，显示对话框");
                    runOnUiThread(() -> {
                        hideLoading();
                        showInvalidDeviceDialog(readableCount, writableCount);
                    });
                    return;
                }

                Log.d("DeviceDetail", "特征值数量符合要求，继续连接");
                runOnUiThread(() -> showLoading("正在读取特征值..."));
                readCharacteristics(gatt);
                handler.post(readRunnable);
            } else {
                Log.e("DeviceDetail", "服务发现失败，状态: " + status);
                runOnUiThread(() -> {
                    hideLoading();
                    showError("获取服务失败");
                });
            }
        }
        private void updateLightEffect(float lightValue) {
            // 将光照值映射到0-1的范围，可以根据实际光照值范围调整
            float alpha = Math.min(lightValue / 1000f, 1.0f);

            // 使用动画使过渡更平滑
            ObjectAnimator animator = ObjectAnimator.ofFloat(circle, "alpha", circle.getAlpha(), alpha);
            animator.setDuration(500); // 500ms的过渡时间
            animator.setInterpolator(new LinearInterpolator());
            animator.start();
        }
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                byte[] data = characteristic.getValue();
                String asciiValue = DataConverter.bytesToAscii(data);

                runOnUiThread(() -> {
                    hideLoading();
                    // 更新到 light TextView
                    light.setText("Light: " + asciiValue);
//                    characteristicAdapter.updateCharacteristicValue(
//                        characteristic.getUuid().toString(),
//                        asciiValue  // 直接传递ASCII值
//                    );
                    try {
                        float lightValue = Float.parseFloat(asciiValue.trim());
                        updateLightEffect(lightValue);
                    } catch (NumberFormatException e) {
                        circle.setAlpha(0.5f); // 默认透明度
                    }
                });
            } else {
                runOnUiThread(() -> {
                    hideLoading();
                    showError("读取特征值失败");
                });
            }
        }
        // 添加写特征值的方法
        private void writeCharacteristic(String value) {

        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                          BluetoothGattCharacteristic characteristic) {
            byte[] data = characteristic.getValue();
            String value = bytesToHexString(data);
            runOnUiThread(() -> {
                characteristicAdapter.updateCharacteristicValue(
                    characteristic.getUuid().toString(),
                    value
                );
            });
        }
    };

    private String bytesToHexString(byte[] data) {
        if (data == null || data.length == 0) {
            return "空值";
        }

        StringBuilder sb = new StringBuilder();
        for (byte b : data) {
            sb.append(String.format("%02X ", b));
        }

        // 尝试解析为ASCII字符串
        try {
            String asciiStr = new String(data, "ASCII").trim();
            if (isPrintableAscii(asciiStr)) {
                return sb.toString() + " (ASCII: " + asciiStr + ")";
            }
        } catch (Exception e) {
            // 解析失败，仅返回十六进制
        }

        return sb.toString();
    }

    private boolean isPrintableAscii(String str) {
        for (char c : str.toCharArray()) {
            if (c < 32 || c > 126) {
                return false;
            }
        }
        return true;
    }

    private void readCharacteristics(BluetoothGatt gatt) {
        for (BluetoothGattService service : gatt.getServices()) {
            if (service.getUuid().toString().equals(targetServiceUuid)) {
                List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
                runOnUiThread(() -> {
                    characteristicAdapter.updateCharacteristics(characteristics);
                });

                // 依次读取每个特征值
                for (BluetoothGattCharacteristic characteristic : characteristics) {
                    if (ActivityCompat.checkSelfPermission(this, 
                        Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                        // 检查特征值是否支持读取
                        if ((characteristic.getProperties() & 
                            BluetoothGattCharacteristic.PROPERTY_READ) != 0) {
                            gatt.readCharacteristic(characteristic);
                        }
                        
                        // 检查特征值是否支持通知
                        if ((characteristic.getProperties() & 
                            BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
                            gatt.setCharacteristicNotification(characteristic, true);
                        }
                    }
                }
                break;
            }
        }
    }

    private void showError(String message) {
        hideLoading();
        Snackbar.make(characteristicsList, message, Snackbar.LENGTH_LONG).show();
    }

    private void showInvalidDeviceDialog(int readableCount, int writableCount) {
        Log.d("DeviceDetail", "显示不兼容对话框");
        String message = String.format(
            "此设备的目标服务（%s）特征值数量不符合要求：\n\n" +
            "• 可读特征值：%d个（需要1个）\n" +
            "• 可写特征值：%d个（需要1个）\n\n" +
            "请选择具有正确特征值数量的设备。",
            targetServiceUuid,
            readableCount, writableCount
        );

        new MaterialAlertDialogBuilder(this)
            .setTitle("设备不兼容")
            .setMessage(message)
            .setPositiveButton("返回", (dialog, which) -> {
                Log.d("DeviceDetail", "用户点击返回按钮");
                disconnectAndFinish();
            })
            .setCancelable(false)
            .show();
    }

    private void disconnectAndFinish() {
        Log.d("DeviceDetail", "开始断开连接");
        if (bluetoothGatt != null) {
            if (ActivityCompat.checkSelfPermission(this, 
                Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                bluetoothGatt.disconnect();
                bluetoothGatt.close();
                Log.d("DeviceDetail", "蓝牙连接已断开");
            }
            bluetoothGatt = null;
        }
        Log.d("DeviceDetail", "结束Activity");
        finish();
    }

    @Override
    protected void onDestroy() {
        handler.removeCallbacks(readRunnable);
        super.onDestroy();
        if (bluetoothGatt != null) {
            if (ActivityCompat.checkSelfPermission(this, 
                Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                bluetoothGatt.close();
            }
            bluetoothGatt = null;
        }
    }
}